<?php

class Admin_ResultatController extends Zend_Controller_Action
{

    public function init()
    {
		if(!Zend_Auth::getInstance()->hasIdentity())  
		{
			$this->_redirect('admin/login');  
		}  
    }

    public function indexAction()
    {
    	$grandprixDAO = new Application_Model_GrandprixDAO();
        $this->view->grandprix = $grandprixDAO->findAll();
    }
    
    public function addAction()
    {
    	$id = $this->getRequest()->getParam('id');
    	$grandprixDAO = new Application_Model_GrandprixDAO();
    	$piloteDAO = new Application_Model_PiloteDAO();
    	$courseDAO = new Application_Model_CourseDAO();
    	$pointsDAO = new Application_Model_PointsDAO();
    	$this->view->points=$pointsDAO->findAll();
		$this->view->grandprix = $grandprixDAO->findAll();
		$grandprix = $grandprixDAO->find($id);
        $this->view->gp = $grandprix;
        $form = new Application_Form_Resultat();
        $this->view->form=$form;
		if($this->getRequest()->isPost())
		{
			$formData = $this->getRequest()->getPost();
			if($form->isValid($formData))
			{
				$values = $form->getValues();
				$course = new Application_Model_Course();
				$course->setGpNum($id);
				$course->setPilote($piloteDAO->find($values['pilnum']));
				$course->setTempsCourse($values['tempscourse']);

				if($courseDAO->save($course))
				{
					$this->_redirect('admin/resultat/'.$id);
				}
				else
				{
					$this->view->message="<div id='popup' class='hidden' title='Erreur'>Ce pilote est déjà dans la course</div>";
					$form->populate($values);
				}
			}
			else
			{
				$form->populate($form->getValues());
			}
		}
    }
}